package com.lyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyj.exception.BaseException;
import com.lyj.mapper.DeviceRoomMappingMapper;
import com.lyj.mapper.RoomMapper;
import com.lyj.pojo.DeviceRoomMapping;
import com.lyj.pojo.Room;
import com.lyj.pojo.dto.RoomAddDTO;
import com.lyj.pojo.dto.RoomEditDTO;
import com.lyj.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private DeviceRoomMappingMapper deviceRoomMappingMapper;

    @Override
    public List<Room> getRoomList(Integer familyId) {
        // 验证家庭ID
        if (familyId == null) {
            throw new BaseException("家庭ID不能为空");
        }

        // 查询该家庭的所有房间
        return roomMapper.selectByFamilyId(familyId);
    }

    @Transactional
    @Override
    public Integer addRoom(RoomAddDTO roomAddVO) {
        // 检查房间名称是否已存在
        Integer count = roomMapper.countByFamilyIdAndRoomName(
                roomAddVO.getFamilyId(),
                roomAddVO.getRoomName()
        );

        if (count != null && count > 0) {
            throw new BaseException("该房间名称已存在");
        }

        // 创建房间实体并保存
        Room room = new Room();
        room.setFamilyId(roomAddVO.getFamilyId());
        room.setRoomName(roomAddVO.getRoomName());

        roomMapper.insert(room);

        // 返回新创建的房间ID
        return room.getRoomId();
    }

    @Transactional
    @Override
    public void editRoom(RoomEditDTO roomEditVO, Integer operatorFamilyId) {
        // 验证房间是否存在
        Room room = roomMapper.selectById(roomEditVO.getRoomId());
        if (room == null) {
            throw new BaseException("房间不存在");
        }

        // 验证操作权限（确保属于同一家庭）
        if (!room.getFamilyId().equals(operatorFamilyId)) {
            throw new BaseException("无权限操作此房间");
        }

        // 检查新名称是否已存在
        Integer count = roomMapper.countByFamilyIdAndRoomName(
                operatorFamilyId,
                roomEditVO.getRoomName()
        );

        if (count != null && count > 0) {
            throw new BaseException("该房间名称已存在");
        }

        // 更新房间名称
        room.setRoomName(roomEditVO.getRoomName());
        roomMapper.updateById(room);
    }

    @Transactional
    @Override
    public void deleteRoom(Integer roomId, Integer operatorFamilyId) {
        // 1. 验证房间是否存在
        Room room = roomMapper.selectById(roomId);
        if (room == null) {
            throw new BaseException("房间不存在");
        }

        // 2. 验证操作权限（确保属于同一家庭）
        if (!room.getFamilyId().equals(operatorFamilyId)) {
            throw new BaseException("无权限操作此房间");
        }

        // 3. 检查该房间下是否有关联设备
        List<DeviceRoomMapping> mappings = deviceRoomMappingMapper.selectByRoomId(roomId);
        if (!mappings.isEmpty()) {
            // 3.1 获取默认房间（可根据业务设定，如"未分配"房间）
            Room defaultRoom = roomMapper.selectDefaultRoom(operatorFamilyId);
            if (defaultRoom == null) {
                // 3.2 如果没有默认房间则创建一个
                defaultRoom = new Room();
                defaultRoom.setFamilyId(operatorFamilyId);
                defaultRoom.setRoomName("未分配");
                roomMapper.insert(defaultRoom);
            }

            // 3.3 将关联设备迁移到默认房间
            for (DeviceRoomMapping mapping : mappings) {
                mapping.setRoomId(defaultRoom.getRoomId());
                deviceRoomMappingMapper.updateById(mapping);
            }
        }

        // 4. 执行房间删除
        roomMapper.deleteById(roomId);
    }

}
